<template>
  <el-select
    v-model="value"
    filterable
    allow-create
    remote
    @change="handleChange"
    reserve-keyword
    :placeholder="placeholder"
    :remote-method="handleRemoteSearch"
    :loading="loading"
    style="width: 100%"
  >

    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select>
</template>

<script setup lang="ts">
interface Props {
    modelValue: any,
    placeholder: string,
    remoteSearch: (query: string)=>Promise<{
        value: any;
        label: any;
    }[]>
    // getData: (page:number)=>Promise<{
    //     value: any;
    //     label: any;
    // }[]>
}

const emit = defineEmits(["update:modelValue","update"])
const value = computed({
    get:()=>props.modelValue,
    set:(val)=>emit("update:modelValue",val)
       
})
const props = defineProps<Props>()
const page = ref(1)
const loading = ref(false);
const options = ref<{ value: any; label: any }[]>([]);


onMounted(()=>{
  if (props.modelValue) {
    handleRemoteSearch(props.modelValue) 
  }
})
async function handleRemoteSearch(query: string) {
  if (query) {
    loading.value = true;
    const result =  await props.remoteSearch(query)
    console.log("search result:",result)
    options.value = result
    console.log("options value",options.value)
    loading.value = false;
  } else {
    // options.value = await props.getData(page);
    options.value = []
  }
}

function handleChange(value:any){
    emit("update",value)
}
</script>

<style scoped></style>
